import React, { useState, useEffect } from 'react';
import { Space } from 'antd';
import { Button, Table, Form, Input, Select } from 'antd';
import { useHistory } from "react-router-dom";
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import service from '../../../utils/service';
import { DataType } from "../model/index";
import { searchList } from '../myHooks/security';

const data: DataType[] = [];
export default function () {
    const [form] = Form.useForm();
    const columns: ColumnsType<DataType> = [
        {
            title: '保安姓名',
            dataIndex: 'staffName',
            key: 'staffName'
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex'
        },
        {
            title: '保安证编号',
            dataIndex: 'staffNum',
            key: "staffNum "
        },
        {
            title: '年龄',
            dataIndex: 'staffAge',
            key: "staffAge "
        },
        {
            title: '聘用性质',
            dataIndex: 'nature',
            key: "nature "
        },
        {
            title: '联系电话',
            dataIndex: 'phone',
            key: "phone "
        },
        {
            title: '更新时间',
            dataIndex: 'uptimeTime',
            key: "uptimeTime "
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: "action",
            render: (_, data) => (
                <Space>
                    <Button onClick={() => { toEditor(data) }}>编辑</Button>
                    <Button onClick={() => { toDelete(data.id) }}>删除</Button>
                </Space>
            )

        },

    ];

    const toDelete = (id: number) => {
        service({
            url: "/security/" + id,
            method: "delete",
        }).then(
            (res) => {
                alert("删除成功！");
                searchList(setData, setLength);
            }
        )

    }
    useEffect(() => {
        searchList(setData, setLength);
        //发请求修改表格数据状态
        /*  service({
             url: "/security",
             method: "get",
 
         }).then(
             res => {
                 console.log("res", res);
                 //给每条数据加key
                 res.data.forEach(
                     (element: DataType, index: number) => {
                         element.key = index + ''
                     }
                 )
                 //修改表格数据状态
                 setData(res.data);
             }) */
    }, [])
    const [newData, setData] = useState(data);
    const [newDataLength, setLength] = useState(0);
    const history = useHistory();
    //搜索
    const onFinish = (values: any) => {
        console.log('Success:', values);
        //收集数据
        let value: any = {};
        //判断当前键的值是否为undefined
        for (var key in values) {
            if (values[key]) {
                value[key] = values[key]
            }
        }

        //发请求
        service({
            url: "/security",
            method: 'get',
            params: value
        }).then(
            (res) => {
                console.log("res", res);
                res.data.forEach((element: any, index: number) => {
                    element.key = '' + index

                });
                setData(res.data);
                setLength(res.data.length)
            }
        )
    };
  
    //去添加页面
    function toAdd() {
        history.push("/Main/AddSecurityStaff")
    }
    //重置
    const onReset = () => {
        form.resetFields();
        console.log("onReset");
    };
    // 去编辑页面
    function toEditor(id: DataType) {
        history.push({ pathname: '/Main/EditorSecurityStaff', state: { data: id } });
    }

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    //删除所选
    const toDeletePick = () => {
        const arr: any[] = [];
        
        console.log("selectedRowKeys", selectedRowKeys);
       //遍历表格数据
       //判断当前项的索引在选中的数组里，在的话就发请求删去，不在的话就留下了
        
        newData.forEach((element:DataType,index:number) => {
            if (selectedRowKeys.includes((index + ""))) {
                service({
                    url: "/security/" + element.id,
                    method: "delete",                 
                }).then(
                    (res) => {
                        if (res.status === 200) {
                            console.log("删除成功");                            
                        }
                        
                    }
                )

               
            } else {
                arr.push(element);
                
            }
            setData(arr);
            setLength(arr.length);
       }) 
    }

    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };
    return (
        <div style={{ height: "100%", width: "100%", background: "pink" }}>
            <header>
                <h1>
                    保安管理
                </h1>
            </header>
            <div className="bigbox">
                <div className="form" style={{ display: "flex" }}>

                    <Form
                        form={form}
                        /* name="control-hooks" */
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600, display: "flex" }}
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            label=""
                            name="staffName"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="sex"
                        >
                            <Select
                                defaultValue="性别"
                                style={{ width: 120 }}

                                options={[
                                    { value: '全部', label: '全部' },
                                    { value: '男', label: '男' },
                                    { value: '女', label: '女' },

                                ]}
                            />
                        </Form.Item>

                        <Form.Item name="nature" >
                            <Select
                                defaultValue="聘用性质"
                                style={{ width: 120 }}
                                /* onChange={handleChange} */
                                options={[
                                    { value: '全部', label: '全部' },
                                    { value: '自聘', label: '自聘' },
                                    { value: '代理', label: '代理' },
                                    { value: '委派', label: '委派' },
                                ]}
                            />

                        </Form.Item>

                        <Form.Item /* wrapperCol={{ offset: 8, span: 16 }} */ style={{ display: "flex" }}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>

                        </Form.Item>
                        <Button htmlType="button" onClick={onReset}>
                            重置
                        </Button>
                    </Form>
                    <Button onClick={toAdd}>+新增保安</Button>

                </div>
                <div className="number" style={{ display: "flex", justifyContent: "space-between" }}>
                    <h1>
                        {"查询结果:共计" + newDataLength + "条数据"}
                    </h1>
                    <Button onClick={toDeletePick}>删除所选</Button>

                </div>
                <Table rowSelection={rowSelection} columns={columns} dataSource={newData} />
            </div>

        </div>
    )
}
